import 'package:flutter/material.dart';

import '../common/api_service.dart';
import '../model/cartoon_model.dart';
import 'cartoon_list_item.dart';

class CartoonListView extends StatefulWidget {
  final String searchText;

  const CartoonListView({super.key, required this.searchText});

  @override
  State<CartoonListView> createState() => _CartoonListViewState();
}

class _CartoonListViewState extends State<CartoonListView> {
  final List<CartoonModel> _cartoonList = [];

  @override
  void initState() {
    super.initState();

    _searchCartoonList();
  }

  void _searchCartoonList() {
    ApiService().searchCartoonList(widget.searchText, 1, (list) {
      setState(() {
        _cartoonList.clear();
        _cartoonList.addAll(list);
      });
    }, () {});
  }

  Widget _buildListViewItem(BuildContext context, int index) {
    var cartoon = _cartoonList[index];
    return CartoonListItem(cartoon: cartoon);
  }

  @override
  Widget build(BuildContext context) {
    if (_cartoonList.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              "assets/images/icon_empty.png",
              width: 150,
              height: 150,
              fit: BoxFit.cover,
            ),
            const Text(
              "无数据～",
              style: TextStyle(color: Colors.grey, fontSize: 15),
            )
          ],
        ),
      );
    }

    return ListView.builder(itemCount: _cartoonList.length, itemBuilder: _buildListViewItem);
  }
}
